package com.dqp.cslggroup.SubjectView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import androidx.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.MainActivity;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.DialogView;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.GetTimeUtil;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.bean.note;
import com.zhuangfei.timetable.TimetableView;
import com.zhuangfei.timetable.listener.ISchedule;
import com.zhuangfei.timetable.listener.OnSlideBuildAdapter;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.model.ScheduleSupport;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

public class SubjectFragment extends Fragment {
    private TimetableView mTimetableView;
    private Context context;
    private int week;
    private String[] times = new String[]{
            "08:00\n08:50", "09:00\n09:50",
            "10:10\n11:00", "11:10\n12:00",
            "13:30\n14:20", "14:30\n15:20",
            "15:40\n16:30", "16:40\n17:30",
            "18:30\n19:20", "19:30\n20:20",
            "20:40\n21:30", "21:40\n22:30",
            "22:40\n23:30", "23:40\n00:30",
    };
    private boolean showWeekends;
    private boolean isThisWeek;
    private boolean showTime;
    private int length;
    private int jie;
    private int transparency;
    private int timeSize;
    private boolean couples = true;
    private int REQUEST_CODE_CAMERA = 1;
    private String takePhotoPath;
    private ImageView takePhotoImg;
    private static String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.WRITE_CALENDAR,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @SuppressLint("InflateParams")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.timetable_view, null);
        context = view.getContext();
        week = ((MainActivity) context).toValue();
        couples = ((MainActivity) context).toCouples();
        mTimetableView = view.findViewById(R.id.id_timetableView);
        initTimetableView(week);
        EventBus.getDefault().register(this);
        return view;
    }


    /**
     * 更新一下，防止因程序在后台时间过长（超过一天）而导致的日期或高亮不准确问题。
     */
    @Override
    public void onStart() {
        super.onStart();
        mTimetableView.onDateBuildListener().onHighLight();
    }

    private void PreferenceManagerDate() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = sp.edit();
        showWeekends = sp.getBoolean("showWeekends", true);
        isThisWeek = sp.getBoolean("show", false);
        length = sp.getInt("lattice_length", 180);
        jie = sp.getInt("course_jie", 10);
        transparency = sp.getInt("transparency", 3);
        showTime = sp.getBoolean("showTime", true);
        timeSize = sp.getInt("timeSize", 8);
        editor.apply();
    }

    /**
     * 初始化课程控件
     */
    private void initTimetableView(int week) {
        PreferenceManagerDate();
        List<MySubject> mySubjects;
        if (couples) mySubjects = SubjectRepertory.loadSubjects();
        else mySubjects = SubjectRepertory.loadCouplesSubjects();
        mTimetableView.curWeek(week)
                .curTerm(GetTimeUtil.getYear() + "")
                .maxSlideItem(jie)
                .monthWidthDp(25)
                .itemHeight(length)
                .source(mySubjects)
                .itemTextColor(Color.WHITE, true)
                .isShowNotCurWeek(isThisWeek)
                .cornerAll(15)
                .isShowWeekends(showWeekends)
                .isShowFlaglayout(false)
                .alpha(0f, 0f, transparency * 0.1f)
                .callback((ISchedule.OnItemClickListener) (v, scheduleList) -> DialogView.courseMore(context, scheduleList, week, couples, () -> {
                    if (couples) refreshTimeTableView();
                    else refreshCouplesTimeTableView();
                }))
                .callback(this::myNote)
                .showView();
        if (showTime) showTime(timeSize * 1f);
        else hideTime();

    }

    private void myNote(View v, int day, int start) {
        List<Schedule> scheduleList = ScheduleSupport.getHaveSubjectsWithDay(ScheduleSupport.transform(SubjectRepertory.loadSubjects()), week, day - 1);
        for (Schedule s : scheduleList) {
            if (s.getStart() == start) {
                if (EasyPermissions.hasPermissions(context, permissions))
                    DialogView.classNotes(context, s.getName(), day, start, (save, name, data, noteEd, take, img, dialog, noteList) -> {
                        takePhotoImg = img;
                        save.setOnClickListener(v12 -> {
                            UiUtils.hideKeyboard(v);
                            note newNote = new note();
                            newNote.setData(data.getText().toString());
                            newNote.setName(name.getText().toString());
                            newNote.setText(noteEd.getText().toString() + "");
                            newNote.setStart(start);
                            newNote.setWeek(day);
                            newNote.setImg(takePhotoPath);
                            if (noteList.size() > 0)
                                MyApplication.getDaoInstant().getNoteDao().delete(noteList.get(0));
                            MyApplication.getDaoInstant().getNoteDao().insertOrReplace(newNote);
                            dialog.dismiss();
                        });
                        take.setOnClickListener(v1 -> {
                            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                            StrictMode.setVmPolicy(builder.build());
                            builder.detectFileUriExposure();
                            takePhotoPath = Environment.getExternalStorageDirectory().getPath() + "/CSLG_Note" + Calendar.getInstance().getTimeInMillis() + ".jpg";
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri photoUri = Uri.fromFile(new File(takePhotoPath)); // 传递路径
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径
                            startActivityForResult(intent, REQUEST_CODE_CAMERA);
                        });
                    });
                else new AppSettingsDialog.Builder(this)
                        .setTitle("权限申请")
                        .setRationale("您没有授权应用所需的读写相册的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                        .build().show();
            }
        }
    }

    private void refreshTimeTableView() {
        PreferenceManagerDate();
        List<MySubject> mySubjects = SubjectRepertory.loadSubjects();
        mTimetableView
                .source(mySubjects)
                .isShowNotCurWeek(isThisWeek)
                .itemHeight(length)
                .isShowWeekends(showWeekends)
                .maxSlideItem(jie)
                .alpha(0f, 0f, transparency * 0.1f)
                .updateView();
        if (showTime) showTime(timeSize * 1f);
        else hideTime();

    }

    private void refreshCouplesTimeTableView() {
        PreferenceManagerDate();
        List<MySubject> mySubjects = SubjectRepertory.loadCouplesSubjects();
        mTimetableView
                .source(mySubjects)
                .isShowNotCurWeek(isThisWeek)
                .itemHeight(length)
                .isShowWeekends(showWeekends)
                .maxSlideItem(jie)
                .alpha(0f, 0f, transparency * 0.1f)
                .updateView();
        if (showTime) showTime(timeSize * 1f);
        else hideTime();
    }

    /**
     * 显示时间
     * 设置侧边栏构建监听，TimeSlideAdapter是控件实现的可显示时间的侧边栏
     */
    private void showTime(float size) {
        OnSlideBuildAdapter listener = (OnSlideBuildAdapter) mTimetableView.onSlideBuildListener();
        listener.setTimes(times)
                .setTimeTextSize(size);
        mTimetableView.updateSlideView();
    }


    private void hideTime() {
        mTimetableView.callback((ISchedule.OnSlideBuildListener) null);
        mTimetableView.updateSlideView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            Glide.with(context).load(takePhotoPath).into(takePhotoImg);
            takePhotoImg.setVisibility(View.VISIBLE);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("SubjectFragment")) {
            if (event.getRefresh() != null && event.getRefresh())
                refreshTimeTableView();
            if (event.getWhat() == 1) {
                refreshCouplesTimeTableView();
                couples = false;
            }

            if (event.getWhat() == 2) {
                couples = true;
                refreshTimeTableView();
            }
        }


    }

}
